# coding:utf-8
import getpass
import pickle
"""
张斌老师的参考代码
"""

"""
验证一个文本里面的密码，如果正确返回，不正确重试3次，添加注册（用户名和密码）登陆流程，密码文件使用 pickle 标准库保存
"""

def open_database():
    try:
        with open('passwd.pkl', 'rb') as f:
            return pickle.load(f)
    except IOError as e:
        return False
    except Exception as e:
        raise e


def update_database(user_data):
    try:
        with open('passwd.pkl', 'wb') as f:
            pickle.dump(user_data, f)
            return True
    except IOError as e:
        return False
    except Exception as e:
        raise e


def register():
    """
    注册
    {"username": "password"} 
    """
    username = input("请输入用户名：")
    user_data = open_database() if open_database() else {}
    if username in user_data.keys():
        print("用户已经存在！")
        return False
    user_passwd = getpass.getpass("请输入密码：")
    user_data[username] = user_passwd
    db_sataus = update_database(user_data)
    if not db_sataus:
        print("注册失败！")
        return False
    print("注册成功！")

def login():
    """
    登陆
    """
    count =0
    username = input("请输入用户名：")
    user_data = open_database()
    passwd = user_data.get(username)
    if passwd is None:
        print("用户不存在!")
        return False

    while count < 3:
        user_passwd = getpass.getpass("请输入密码：")
        if user_passwd != passwd:
            count += 1
            print("密码错误，请重试，最多3次")
            continue
        print("密码正确!")
        break
    else:  #每次错误print()和break就会杯continue掉，然后在执行下一次的while，如果三次都错了，也就是while无意外执行完的，才会else执行
        print("重试了3次密码 退出！")

def main():
    while True:
        user_choice = input("1 注册，2 登陆， 0 退出：")
        if user_choice == "1":
            register()
        elif user_choice == "2":
            login()
        else:
            break

if __name__ == '__main__':
    main()